import type { FormRules } from 'naive-ui'
import type { Ref } from 'vue'
import type { NvFormProps } from './types'
import type { RowData } from '@/types'
import { get, set } from 'lodash-es'
import { computed } from 'vue'

export function useInit(props: NvFormProps, formData: Ref<RowData>) {
  function setDefaultValues() {
    if (props.mode === 'view')
      return
    console.debug('setDefaultValues')
    for (const [field, fieldOption] of Object.entries(props.option.fields)) {
      set(formData.value, field, get(formData.value, field) ?? fieldOption.defaultValue)
    }
  }
  setDefaultValues()

  const formRules = computed<FormRules>(() => {
    if (props.mode === 'view')
      return {}
    console.debug('computed formRules')
    const rules: FormRules = {}
    for (const [field, fieldOption] of Object.entries(props.option.fields)) {
      fieldOption.rule && (rules[field] = fieldOption.rule)
    }
    return rules
  })

  return { formRules }
}
